package com.seetaface.service;

import com.cnsugar.ai.face.FaceHelper;

import static com.seetaface.common.exception.util.ServiceExceptionUtil.exception;

import com.seetaface.common.exception.enums.ErrorCodeConstants;
import com.seetaface.model.FaceAntiSpoofingStatus;
import com.seetaface.model.SeetaRect;
import com.seetaface.pojo.FaceResultRequest;
import org.springframework.stereotype.Service;
import lombok.SneakyThrows;

/**
 * @Author SUN
 * @Description
 * @Data 2023/3/28 15:05
 */
@Service
public class SeetafaceServiceImpl implements SeetafaceService{

    @Override
    @SneakyThrows
    public FaceResultRequest register(String key, byte[] imge) {
        FaceResultRequest request;
        try {
            request = this.faceResult(imge);
            if(request.getEnvironment()){
                request.setRegister(FaceHelper.register(key, imge));
            }else {
                throw exception(ErrorCodeConstants.GET_HY_PRODUCT_LIST_FAIL);
            }
            return request;
        } catch (Exception e) {
            throw exception(ErrorCodeConstants.GET_HY_PRODUCT_LIST_FAIL);
        }
    }

    /**
     * 活体检测和环境检测
     * @param imge
     * @return
     */
    private FaceResultRequest faceResult (byte[] imge) {
        FaceResultRequest result = new FaceResultRequest();
        //活体检测
        FaceAntiSpoofingStatus status = FaceHelper.predictImage(imge);
        if (status.equals(FaceAntiSpoofingStatus.REAL)){
            //图片检测
            SeetaRect[] rects = FaceHelper.detect(imge);
            if (rects.length>1){
                result.setEnvironment(Boolean.FALSE);
            }else {
                result.setEnvironment(Boolean.TRUE);

            }
        }
        result.setStatus(status);
        return result;
    }

    @Override
    public FaceResultRequest seach(byte[] imge) {
        FaceResultRequest result = this.faceResult(imge);
        //真人识别
        if(result.getEnvironment()) {
            result.setResult(FaceHelper.search(imge));
        }else {
            throw exception(ErrorCodeConstants.GET_HY_PRODUCT_LIST_FAIL);
        }
        return result;
    }

}
